//
//  GSCommonFindPasswordController.m
//  GSLoginDemo
//
//  Created by guoshikeji_a on 2018/7/27.
//  Copyright © 2018年 guoshikeji. All rights reserved.
//

#import "GSCommonFindPasswordController.h"

#import "GSCommonLoginPhoneTextField.h"

#import "GSCommonFindPassSmsVerifyController.h"

#import "NSString+RegexCategory.h"

//request
#import "BCCheckUserRegisterdRequest.h"//找回密码 检查用户是否已经注册
#import "BCPhoneCaptchaRequest.h"//请求发送手机验证码
#import "BCEmailCaptchaRequest.h"//请求发送邮箱验证码

@interface GSCommonFindPasswordController ()

@property (nonatomic, strong) GSCommonLoginPhoneTextField *phoneTF;

@end

@implementation GSCommonFindPasswordController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.largeTitleLabel.text = GSLoginLocalized(@"Find Password");
    NSString *phone = GSLoginLocalized(@"Phone or Email");
    NSString *subStr = GSLoginLocalizedFormatString(@"Please input %@ to finished finding password!",phone);
    NSMutableAttributedString *attriText = [[NSMutableAttributedString alloc] initWithString:subStr];
    NSRange range = [subStr rangeOfString:phone];
    if (range.location!=NSNotFound) {
        [attriText addAttributes:@{NSForegroundColorAttributeName:GSLOGIN_THEME_COLOR} range:range];
    }
    self.subTitleLabel.attributedText = attriText;
    [self setupSubviews];
    
    //
    __weak typeof(self) wself = self;
    self.phoneTF.phoneInvalidBlock = ^(BOOL valid) {
        if (wself.doneButton.enabled != valid) {
            wself.doneButton.enabled = valid;
        }
    };
    
    //唤起输入
    [self.phoneTF becomeFirstResponder];
}

- (void)setupSubviews {
    self.phoneTF = [GSCommonLoginPhoneTextField new];
    self.phoneTF.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.phoneTF.adjustsFontSizeToFitWidth = true;
    self.phoneTF.autocorrectionType = UITextAutocorrectionTypeNo;
    self.phoneTF.tintColor = self.phoneTF.textColor;
    self.phoneTF.attributedPlaceholder = [[NSAttributedString alloc] initWithString:GSLoginLocalized(@"Input Phone or Email") attributes:@{NSForegroundColorAttributeName:GSLOGIN_TEXTFIELD_PLACEHOLDER_COLOR,NSFontAttributeName:[UIFont systemFontOfSize:38 weight:UIFontWeightLight]}];
    self.phoneTF.keyboardType = UIKeyboardTypeEmailAddress;
    self.phoneTF.font = [UIFont systemFontOfSize:40 weight:UIFontWeightRegular];
    [self.view addSubview:self.phoneTF];
    [self.phoneTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.largeTitleLabel.mas_bottom).offset(55.0);
        make.left.mas_equalTo(self.view).offset(18.0);
        make.right.mas_equalTo(self.view).offset(-18.0);
        make.height.mas_equalTo(56.0);
    }];
    self.phoneTF.inputAccessoryView = [UIView new];
    //
    UIView *sepLine = [UIView new];
    sepLine.backgroundColor = GSLOGINRGBRGBHEX(0xF3F3F3);
    [self.view addSubview:sepLine];
    [sepLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.phoneTF.mas_bottom).offset(3.0);
        make.left.mas_equalTo(self.view).offset(10.0);
        make.right.mas_equalTo(self.view);
        make.height.mas_equalTo(2.0);
    }];
    //
    [self.view addSubview:self.doneButton];
    self.doneButton.enabled = false;
    [self.doneButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(sepLine.mas_bottom).offset(40.0);
        make.centerX.mas_equalTo(self.view);
        make.size.mas_equalTo([GSCommonLoginButton defaultSize]);
    }];
}

#pragma mark -
- (void)doneButtonDidClickedAction {
    [self.view endEditing:true];
    if ([self checkUserName]) {
        [self requestUserNameCheckNot:self.phoneTF.phoneNumber];
    }
}
//校验用户账户
- (BOOL)checkUserName {
    GSCCommonLoginAccountType type = [NSString gscLoginAccountTypeWithString:self.phoneTF.phoneNumber];
    if (type==GSCCommonLoginAccountTypeUnknown) {
        NSString *errorMsg = GSLoginLocalized(@"phone or email format error");
        NSString *detailMsg = nil;
        [QMUITips showError:errorMsg detailText:detailMsg inView:self.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errorMsg]];
        return false;
    }
    return true;
}
//请求该用户是否已经存在
- (void)requestUserNameCheckNot:(NSString *)field {
    [self.view showLoginToast];
    BCCheckUserRegisterdRequest *request = [BCCheckUserRegisterdRequest new];
    request.field = field;
    //
    WEAK_SELF
    [request didRequestSuccessed:^(id result, id page) {
        [wself requestCaptchaAction];
    }];
    [request didRequestFailed:^(NSError *error) {
        [wself.view hideLoginToast];
        if (error&&wself.view) {
            NSString *msg = error.domain;
            [QMUITips showError:msg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:msg]];
        }
    }];
    [request requestServer];
}
//请求验证码
- (void)requestCaptchaAction {
    NSString *username = self.phoneTF.phoneNumber;
    GSCCommonLoginAccountType type = [NSString gscLoginAccountTypeWithString:username];
    if (type==GSCCommonLoginAccountTypePhone) {
        [self requestPhoneCaptcha:username];
    }else {
        [self requestEmailCaptchaAddress:username];
    }
}
//发送手机验证码
- (void)requestPhoneCaptcha:(NSString *)phone {
    BCPhoneCaptchaRequest *requst = [BCPhoneCaptchaRequest new];
    requst.phone = phone;
    //
    WEAK_SELF
    [requst didRequestCompleted:^{
        [wself.view hideLoginToast];
    }];
    [requst didRequestSuccessed:^(id result, id page) {
        [wself findPasswordGetCaptchaSuccessAction];
    }];
    [requst didRequestFailed:^(NSError *error) {
        if (error&&wself.view) {
            NSString *msg = error.domain;
            [QMUITips showError:msg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:msg]];
        }
    }];
    [requst requestServer];
}
//发送邮箱验证码
- (void)requestEmailCaptchaAddress:(NSString *)email {
    BCEmailCaptchaRequest *request = [BCEmailCaptchaRequest new];
    request.email = email;
    WEAK_SELF
    [request didRequestCompleted:^{
        [wself.view hideLoginToast];
    }];
    [request didRequestSuccessed:^(id result, id page) {
        [wself findPasswordGetCaptchaSuccessAction];
    }];
    [request didRequestFailed:^(NSError *error) {
        if (error&&wself.view) {
            NSString *msg = error.domain;
            [QMUITips showError:msg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:msg]];
        }
    }];
    [request requestServer];
}

- (void)findPasswordGetCaptchaSuccessAction {
    //更新数据
    NSString *account = self.phoneTF.phoneNumber;
    [GSCommonLoginDataManager sharedData].findPassModel.phoneNumber = account;
    //
    GSCommonFindPassSmsVerifyController *findPassSmsVC = [GSCommonFindPassSmsVerifyController new];
    [self.navigationController pushViewController:findPassSmsVC animated:true];
}

@end
